//
//  PaperListViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/1.
//  Copyright © 2018年 李胜锋. All rights reserved.
//


import RxDataSources
import RxSwift

class PaperListViewController: ViewController, Refreshable, LeftBarButtonItemable, NullData {
    
    // viewModel
    var viewModel = PaperListViewModel()
    
    // view
    var tableView: UITableView!
    var  dataSource: RxTableViewSectionedReloadDataSource<PaperListSection>!
    
    
    //试题类型（标题, classId）
    private var examClass: (String, Int)
    
    init(_ examClass: (String, Int)) {
        self.examClass = examClass
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = examClass.0
        viewModel.classId = examClass.1
        
        initUI()
        bindUI()
        
        tableView.mj_header.beginRefreshing()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setPopRecognizerEnable(true)
    }
    
    func initUI() {
        
        setLeftItem()
        view.backgroundColor = UIColor.lsf_color16(0xf9f9f9)
        tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        tableView.backgroundColor = UIColor.lsf_color16(0xf9f9f9)
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (maker) in
            maker.edges.equalTo(safeAreaInsets())
        }
        
        tableView.separatorStyle = .none
        tableView.rowHeight = 110
        tableView.sectionHeaderHeight = 54
        
        tableView.register(PaperListCell.classForCoder(), forCellReuseIdentifier: "PaperListCell")
        
        
    }
    
    func bindUI() {
        dataSource = RxTableViewSectionedReloadDataSource.init(configureCell: { (ds, tv, ip, item) -> UITableViewCell in
            let cell = self.cell(tv, ip, item)
            return cell
            
        }, titleForHeaderInSection: { (ds, idx) in
            return ds.sectionModels[idx].header
        })
        
        
        viewModel.vmDatas.asObservable().bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)
        
        ///空数据处理
        viewModel.isNull.asObservable().subscribe(onNext: { [weak self] (isNull) in
            if isNull {
                let nilView = self?.nilView()
                self?.tableView.backgroundView = nilView
            }
            else {
                self?.tableView.backgroundView = nil
            }
        }).disposed(by: disposeBag)
        
        tableView.rx.itemSelected.subscribe(onNext: { [weak self] (indexPath) in
            self?.tableView.deselectRow(at: indexPath, animated: true)
        }).disposed(by: disposeBag)
        
        tableView.rx.modelSelected(PaperListModel.self).subscribe(onNext: { [weak self] (item) in
            self?.start(item)
        }).disposed(by: disposeBag)
        
        initRefresh(tableView, headerBlock: {[weak self] in
            self?.viewModel.requestCommand.onNext(true)
        }) {[weak self] in
            self?.viewModel.requestCommand.onNext(false)
        }
        
        ///自动更新刷新状态
        viewModel.autoSetRefreshStatus(header: tableView.mj_header, footer: tableView.mj_footer).disposed(by: disposeBag)
    }
 
    
    
    func cell(_ tableView: UITableView, _ indexPath: IndexPath, _ item: PaperListModel) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PaperListCell") as! PaperListCell
        
        let title = item.title
        let price = item.price ?? 0
        let itemNum = item.itemNum
        let status = item.userStatus
        cell.set(title: title, price: price, itemNum: itemNum, status: status, startClick: { [weak self] aCell in
            self?.start(item)
        }) { [weak self] aCell in
            self?.trial(item)
        }
        return cell
    }
    
}

extension PaperListViewController {
    
    ///点击开始
    func start(_ item: PaperListModel) {
        //检查登录
        if login() == false {  return }
        
        let price = item.price ?? 0
        //已经购买、免费。直接进入试卷
        if price == 0 ||
            item.userStatus == .bought ||
            item.userStatus == .free {
            enterPaper(item)
        }
            //弹出购买
        else {
            RechargeAlert.init(paperId: item.id! ,price: price, presentController:self, compelete: { [weak self] (result) in
                if result {
                    item.userStatus = .bought
                    self?.tableView.reloadData()
                    self?.enterPaper(item)
                }
            }).show()
        }
    }
    
    
    ///点击试用
    func trial(_ item: PaperListModel) {
        //检查登录
        if login() == false {  return }
        
        enterPaper(item, status:.trial)
    }
    
    //进入试卷
    func enterPaper(_ item: PaperListModel, status: PaperStatus = .bought) {
        guard let id = item.id else { return }
        guard let title = item.title else { return }
        let paperVC = PaperViewController.startPaper(id, status: status, title: title)
        navigationController?.pushViewController(paperVC, animated: true)
    }
    
    func login() -> Bool {
        let isLogin = AccountStorage.default.isLogin()
        if isLogin == false {
            showLogin(controller: self, dismissHandle: { [weak self] (result) in
                if result {
                    //清空数据
                    self?.viewModel.vmDatas.value.removeAll()
                    self?.tableView.mj_header.beginRefreshing()
                }
            })
        }
        
        return isLogin
    }
}


